<template>
  <div class="dashboard">
    <!-- 指标卡片 -->
    <div class="metrics">
      <div class="metric-card" v-for="(metric, index) in metrics" :key="index">
        <div class="metric-header">
          <div>
            <div class="metric-value">{{ metric.value }}</div>
            <div class="metric-title">{{ metric.title }}</div>
          </div>
          <div class="metric-icon" :class="metric.color">
            <i :class="metric.icon"></i>
          </div>
        </div>
        <div class="metric-change" :style="{ color: metric.change.startsWith('+') ? '#4cc9f0' : '#f72585' }">
          {{ metric.change }} 相比上月
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts">
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">销售趋势</div>
          <div class="chart-actions">
            <i class="fas fa-ellipsis-h"></i>
          </div>
        </div>
        <div class="chart" ref="salesChart"></div>
      </div>
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">用户访问量</div>
          <div class="chart-actions">
            <i class="fas fa-ellipsis-h"></i>
          </div>
        </div>
        <div class="chart" ref="usersChart"></div>
      </div>
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">产品分布</div>
          <div class="chart-actions">
            <i class="fas fa-ellipsis-h"></i>
          </div>
        </div>
        <div class="chart" ref="productsChart"></div>
      </div>
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">性能指标</div>
          <div class="chart-actions">
            <i class="fas fa-ellipsis-h"></i>
          </div>
        </div>
        <div class="chart" ref="performanceChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts';

// 使用组合式函数重构代码
const useDarkMode = () => {
  const darkMode = ref(false);
  
  const toggleTheme = () => {
    darkMode.value = !darkMode.value;
    document.body.classList.toggle('dark-mode', darkMode.value);
    localStorage.setItem('theme', darkMode.value ? 'dark' : 'light');
  };
  
  // 初始化主题
  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark') {
      darkMode.value = true;
      document.body.classList.add('dark-mode');
    }
  };
  
  return {
    darkMode,
    toggleTheme,
    initTheme
  };
};

const useMetrics = () => {
  const metrics = ref([
    { title: '总用户数', value: '12,845', icon: 'fas fa-users', change: '+12%', color: 'bg-primary' },
    { title: '总收入', value: '$24,845', icon: 'fas fa-dollar-sign', change: '+18%', color: 'bg-success' },
    { title: '新订单', value: '1,235', icon: 'fas fa-shopping-cart', change: '+8%', color: 'bg-warning' },
    { title: '待处理', value: '142', icon: 'fas fa-tasks', change: '-3%', color: 'bg-info' }
  ]);
  
  return {
    metrics
  };
};

const useCharts = (darkMode) => {
  const salesChart = ref(null);
  const usersChart = ref(null);
  const productsChart = ref(null);
  const performanceChart = ref(null);
  
  let salesChartInstance = null;
  let usersChartInstance = null;
  let productsChartInstance = null;
  let performanceChartInstance = null;
  
  // 初始化图表
  const initCharts = () => {
    const textColor = darkMode.value ? '#f5f6fa' : '#2d3436';
    
    // 销毁现有图表实例
    [salesChartInstance, usersChartInstance, productsChartInstance, performanceChartInstance].forEach(instance => {
      if (instance) instance.dispose();
    });
    
    // 销售趋势折线图
    if (salesChart.value) {
      salesChartInstance = echarts.init(salesChart.value);
      salesChartInstance.setOption({
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月'],
          axisLine: { lineStyle: { color: textColor } },
          axisLabel: { color: textColor }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: textColor } },
          axisLabel: { color: textColor }
        },
        series: [{
          name: '销售额',
          type: 'line',
          smooth: true,
          data: [120, 132, 101, 134, 90, 230, 210],
          itemStyle: { color: '#4361ee' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(67, 97, 238, 0.5)' },
                { offset: 1, color: 'rgba(67, 97, 238, 0)' }
              ]
            }
          }
        }]
      });
    }
    
    // 用户访问柱状图
    if (usersChart.value) {
      usersChartInstance = echarts.init(usersChart.value);
      usersChartInstance.setOption({
        tooltip: { trigger: 'axis' },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          axisLine: { lineStyle: { color: textColor } },
          axisLabel: { color: textColor }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: textColor } },
          axisLabel: { color: textColor }
        },
        series: [{
          name: '活跃用户',
          type: 'bar',
          data: [120, 200, 150, 80, 70, 110, 130],
          itemStyle: { color: '#4cc9f0' }
        }]
      });
    }
    
    // 产品分布饼图
    if (productsChart.value) {
      productsChartInstance = echarts.init(productsChart.value);
      productsChartInstance.setOption({
        tooltip: { trigger: 'item' },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          textStyle: { color: textColor }
        },
        series: [{
          name: '产品分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: darkMode.value ? '#1e1e1e' : '#fff',
            borderWidth: 2
          },
          label: { show: false, position: 'center' },
          emphasis: {
            label: { show: true, fontSize: '18', fontWeight: 'bold' }
          },
          labelLine: { show: false },
          data: [
            { value: 1048, name: '电子产品' },
            { value: 735, name: '服装' },
            { value: 580, name: '家居' },
            { value: 484, name: '食品' },
            { value: 300, name: '其他' }
          ]
        }]
      });
    }
    
    // 性能指标雷达图
    if (performanceChart.value) {
      performanceChartInstance = echarts.init(performanceChart.value);
      performanceChartInstance.setOption({
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.name}<br/>${params.seriesName}: ${params.value.toLocaleString()}`;
          }
        },
        radar: {
          shape: 'circle',
          splitNumber: 5,
          radius: '65%',
          indicator: [
            { name: '销售', max: 7000 },
            { name: '管理', max: 16000 },
            { name: '技术', max: 30000 },
            { name: '支持', max: 40000 },
            { name: '开发', max: 55000 },
            { name: '市场', max: 25000 }
          ],
          axisName: {
            color: textColor,
            backgroundColor: darkMode.value ? 'rgba(30, 30, 30, 0.7)' : 'rgba(255, 255, 255, 0.7)',
            borderRadius: 3,
            padding: [3, 5],
            formatter: (name) => {
              const maxLength = 4;
              return name.length > maxLength ? name.substring(0, maxLength) : name;
            }
          },
          axisLine: {
            lineStyle: {
              color: textColor,
              opacity: 0.6
            }
          },
          axisLabel: {
            color: textColor,
            fontSize: 10,
            formatter: (value) => {
              if (value >= 1000) {
                return (value / 1000).toFixed(0) + 'k';
              }
              return value;
            }
          },
          splitLine: {
            lineStyle: {
              color: darkMode.value ? 'rgba(255, 255, 255, 0.15)' : 'rgba(0, 0, 0, 0.15)',
              type: 'dashed'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: darkMode.value ? ['rgba(255, 255, 255, 0.02)', 'rgba(255, 255, 255, 0.05)']
                : ['rgba(0, 0, 0, 0.02)', 'rgba(0, 0, 0, 0.05)']
            }
          }
        },
        series: [{
          name: '预算 vs 支出',
          type: 'radar',
          emphasis: {
            lineStyle: {
              width: 4
            }
          },
          data: [
            {
              value: [4200, 3000, 20000, 35000, 50000, 18000],
              name: '预算分配',
              areaStyle: {
                color: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.5,
                  colorStops: [
                    { offset: 0, color: 'rgba(67, 97, 238, 0.8)' },
                    { offset: 1, color: 'rgba(67, 97, 238, 0.1)' }
                  ]
                }
              },
              lineStyle: {
                color: '#4361ee',
                width: 2
              },
              itemStyle: {
                color: '#4361ee'
              },
              symbol: 'circle',
              symbolSize: 6
            },
            {
              value: [5000, 14000, 28000, 26000, 42000, 21000],
              name: '实际支出',
              areaStyle: {
                color: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.5,
                  colorStops: [
                    { offset: 0, color: 'rgba(247, 37, 133, 0.8)' },
                    { offset: 1, color: 'rgba(247, 37, 133, 0.1)' }
                  ]
                }
              },
              lineStyle: {
                color: '#f72585',
                width: 2
              },
              itemStyle: {
                color: '#f72585'
              },
              symbol: 'circle',
              symbolSize: 6
            }
          ]
        }]      
      });
    }
  };
  
  // 响应窗口大小变化
  const handleResize = () => {
    [salesChartInstance, usersChartInstance, productsChartInstance, performanceChartInstance].forEach(instance => {
      if (instance) instance.resize();
    });
  };
  
  // 清理图表实例
  const cleanupCharts = () => {
    [salesChartInstance, usersChartInstance, productsChartInstance, performanceChartInstance].forEach(instance => {
      if (instance) instance.dispose();
    });
  };
  
  return {
    salesChart,
    usersChart,
    productsChart,
    performanceChart,
    initCharts,
    handleResize,
    cleanupCharts
  };
};

export default {
  name: 'EChartsDashboard',
  setup() {
    // 使用组合式函数
    const { darkMode, toggleTheme, initTheme } = useDarkMode();
    const { metrics } = useMetrics();
    const { 
      salesChart, 
      usersChart, 
      productsChart, 
      performanceChart, 
      initCharts, 
      handleResize, 
      cleanupCharts 
    } = useCharts(darkMode);
    
    onMounted(() => {
      initTheme();
      nextTick(() => {
        initCharts();
        window.addEventListener('resize', handleResize);
      });
    });
    
    onUnmounted(() => {
      cleanupCharts();
      window.removeEventListener('resize', handleResize);
    });
    
    // 监听暗黑模式变化，重新初始化图表
    watch(darkMode, () => {
      nextTick(() => {
        initCharts();
      });
    });
    
    return {
      darkMode,
      toggleTheme,
      metrics,
      salesChart,
      usersChart,
      productsChart,
      performanceChart
    };
  }
};
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background-color: var(--bg);
  min-height: 100vh;
  transition: var(--transition);
  position: relative;
}

.theme-toggle {
  position: absolute;
  top: 20px;
  right: 20px;
}

.theme-btn {
  background: var(--card-bg);
  border: 1px solid var(--border);
  border-radius: 20px;
  padding: 8px 16px;
  color: var(--text);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: var(--transition);
}

.theme-btn:hover {
  box-shadow: var(--shadow);
  transform: translateY(-2px);
}

/* 指标卡片样式 */
.metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
  
}

.metric-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 20px;
  box-shadow: var(--shadow);
  transition: var(--transition);
}

.metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.metric-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
}

.bg-primary {
  background: rgba(67, 97, 238, 0.2);
  color: var(--primary);
}

.bg-success {
  background: rgba(76, 201, 240, 0.2);
  color: var(--success);
}

.bg-warning {
  background: rgba(247, 37, 133, 0.2);
  color: var(--warning);
}

.bg-info {
  background: rgba(72, 149, 239, 0.2);
  color: var(--info);
}

.metric-value {
  font-size: 1.8rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.metric-title {
  color: var(--text);
  opacity: 0.8;
  font-size: 0.9rem;
}

.metric-change {
  font-size: 0.85rem;
  font-weight: 500;
}

/* 图表区域样式 */
.charts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 20px;
  box-shadow: var(--shadow);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-title {
  font-size: 1.2rem;
  font-weight: 600;
}

.chart {
  height: 300px;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .metrics {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 576px) {
  .dashboard {
    padding: 10px;
  }

  .metrics {
    grid-template-columns: 1fr;
  }
  
  .theme-toggle {
    position: static;
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

<style>
:root {
  --primary: #4361ee;
  --secondary: #3f37c9;
  --success: #4cc9f0;
  --info: #4895ef;
  --warning: #f72585;
  --danger: #e63946;
  --light: #f8f9fa;
  --dark: #212529;
  --text: #2d3436;
  --bg: #f5f6fa;
  --card-bg: #ffffff;
  --border: #dcdde1;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  --transition: all 0.3s ease;
}

body {
  background-color: var(--bg);
  color: var(--text);
  transition: var(--transition);
  margin: 0;
  padding: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

body.dark-mode {
  --text: #f5f6fa;
  --bg: #121212;
  --card-bg: #1e1e1e;
  --border: #2d3436;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
</style>